package com.moodincode.taskcenter.service.impl;

import com.moodincode.taskcenter.bean.TaskInfo;
import com.moodincode.taskcenter.service.IQuartzTaskService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 内存缓存的定时任务
 * @author moodincode
 */
@Service
public class StdQuartzTaskServiceImpl implements IQuartzTaskService {
    /**
     * 内存缓存对象
     */
    public static volatile List<TaskInfo> TASK_INFO_LIST=new ArrayList<>();
    @Override
    public List<TaskInfo> findAll() {
        return TASK_INFO_LIST;
    }

    @Override
    public TaskInfo getById(String id) {

        for (TaskInfo taskInfo : TASK_INFO_LIST) {
            if(taskInfo.getId().equals(id)){
                return taskInfo;
            }
        }
        return null;
    }

    @Override
    public void save(TaskInfo taskInfo) {
        TaskInfo oldTask = getById(taskInfo.getId());
        if(oldTask==null){
            TASK_INFO_LIST.add(taskInfo);
        }else if(!taskInfo.equals(oldTask)){
            BeanUtils.copyProperties(taskInfo,oldTask);
        }

    }

    @Override
    public void delete(String id) {
        TASK_INFO_LIST.removeIf(e->e.getId().equals(id));
    }

    @Override
    public TaskInfo getTaskByJobKey(String name, String group) {

        for (TaskInfo taskInfo : TASK_INFO_LIST) {
            if(taskInfo.getName().equals(name)&&taskInfo.getGroup().equals(group)){
                return taskInfo;
            }
        }
        return null;
    }
}
